package com.itheima.reggie.service.impl;/**
 * 功能描述
 *
 * @author 唯硕
 * @date 2022/09/20  20:51
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 *@ClassName SetmealServiceImpl
 *@Description TODO 套餐类
 *@Author 唯硕
 *@Date 2022/9/20 20:51
 *@Version 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;


    //删除套餐，同时删除套餐对应的菜品关联关系，需要操作两张表：setmeal setmealdish
    @Override
    public void removeWithDish(List<Long> ids) {
//        select count(*) from Setmeal where id in(1,2,3) and status = 1
        //查询套餐状态是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);

        if(count>0){
            //        如果不能删除抛出一个业务异常
            throw  new CustomException("套餐正在售卖中不能删除");
        }


//        如果可以删除先删除套餐表中的数据--setmeal
        this.removeByIds(ids);

//        delete from setmeal_dish where id in(1,2,3)
//        删除关系表中的数据--setmeal--dish
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

    }

    @Transactional
    //添加套餐
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        //保存套餐setmeal表中的信息，执行insert操作
        this.save(setmealDto);

        Long setmealDtoId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDtoId);

            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    }
}
